package com.blyat.xsoft.kernel.component.security;

import com.google.common.base.Strings;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * @author syh
 * @date 2019/8/21
 **/
public class SecurityAccessDecisionManager implements AccessDecisionManager {

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes)
            throws AccessDeniedException, InsufficientAuthenticationException {
        if (CollectionUtils.isEmpty(configAttributes)) {
            throw new AccessDeniedException("无访问权限.");
        }

        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();
            if (Strings.isNullOrEmpty(needRole)) continue;
            boolean hasAuth = authentication.getAuthorities().stream()
                    .filter(auth -> needRole.trim().equals(auth.getAuthority())).count() > 0;
            if (hasAuth) return;
        }
        throw new AccessDeniedException("没有权限访问。");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
